import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';
import type { Vehicle } from './vehicle';

// Transportation 数据接口 (匹配后端 DTO)
export interface Transportation {
  id: number;
  vehicleId: number | null;
  vehicleLicensePlate?: string;
  destination: string;
  createTime: string;
}

// 创建/更新运输记录的 Payload
export interface TransportationPayload {
  id?: number;
  vehicleId: number | null;
  destination: string;
}

// 运输表单字段配置 (options 将在组件中填充)
export const transportationFields = [
  {
    key: 'vehicleId',
    label: '选择车辆',
    type: 'select',
    placeholder: '请选择运输车辆',
    options: [] as { value: number; label: string; disabled?: boolean }[],
  },
  {
    key: 'destination',
    label: '目的地',
    type: 'text',
    placeholder: '请输入目的地',
    maxLength: 100,
  },
];

// 定义车辆选项的接口
export interface VehicleOption {
  value: number;
  label: string;
  disabled?: boolean;
}

export const useTransportationStore = defineStore('transportation', {
  state: () => ({
    transportations: [] as Transportation[],
    loading: false,
    loadingVehicles: false,
  }),
  actions: {
    // 获取运输记录列表
    async fetchTransportations(): Promise<Transportation[]> {
      this.loading = true;
      try {
        const response = await axios.get('/transportations');
        if (response.data.code === 200 && Array.isArray(response.data.data)) {
          const formattedList = response.data.data.map((t: any) => ({
            ...t,
            createTime: t.createTime ? new Date(t.createTime).toLocaleString() : 'N/A',
          }));
          this.transportations = formattedList;
          console.log('Store: Fetched transportations:', formattedList);
          return formattedList;
        }
        throw new Error(response.data.message || '获取运输记录失败');
      } catch (error: any) {
        console.error('Store: 获取运输记录失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法获取运输记录');
        this.transportations = [];
        return [];
      } finally {
        this.loading = false;
      }
    },

    // 获取车辆列表用于 Select
    async fetchVehiclesForSelect(): Promise<Vehicle[]> {
      if (this.loadingVehicles) return [];
      this.loadingVehicles = true;
      try {
        const response = await axios.get('/vehicles');
        if (response.data.code === 200 && Array.isArray(response.data.data)) {
          const vehicles = response.data.data as Vehicle[];
          console.log('Store: Fetched vehicles:', vehicles);
          return vehicles;
        }
        throw new Error(response.data.message || '获取车辆列表失败');
      } catch (error: any) {
        console.error('Store: 获取车辆选项失败:', error);
        ElMessage.error(error.response?.data?.message || '获取车辆选项失败');
        return [];
      } finally {
        this.loadingVehicles = false;
      }
    },

    // 创建运输记录
    async createTransportation(payload: TransportationPayload): Promise<Transportation> {
      try {
        if (!payload.vehicleId || !payload.destination) {
          throw new Error('必须选择车辆并输入目的地');
        }
        const response = await axios.post('/transportations', payload);
        if (response.data.code === 200) {
          console.log('Store: Created transportation:', response.data.data);
          return response.data.data;
        }
        throw new Error(response.data.message || '创建运输记录失败');
      } catch (error: any) {
        console.error('Store: 创建运输记录失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法创建运输记录');
        throw error;
      }
    },

    // 更新运输记录
    async updateTransportation(payload: TransportationPayload): Promise<Transportation> {
      try {
        if (!payload.id || !payload.vehicleId || !payload.destination) {
          throw new Error('更新运输记录时，ID、车辆和目的地不能为空');
        }
        const response = await axios.put('/transportations', payload);
        if (response.data.code === 200) {
          console.log('Store: Updated transportation:', response.data.data);
          return response.data.data;
        }
        throw new Error(response.data.message || '更新运输记录失败');
      } catch (error: any) {
        console.error('Store: 更新运输记录失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法更新运输记录');
        throw error;
      }
    },

    // 删除运输记录
    async deleteTransportation(id: number): Promise<void> {
      try {
        const response = await axios.delete(`/transportations/${id}`);
        if (response.data.code === 200) {
          console.log('Store: Deleted transportation ID:', id);
          return;
        }
        throw new Error(response.data.message || '删除运输记录失败');
      } catch (error: any) {
        console.error('Store: 删除运输记录失败:', error);
        ElMessage.error(error.response?.data?.message || '网络错误，无法删除运输记录');
        throw error;
      }
    },
  },
});